package com.itlz.oss.controller;


import com.itlz.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@Tag(name = "上传课程视频")
public class VideoUploadController {


    @Value("${web.upload-path}")
    private String uploadPath;


    @Operation(summary = "上传课程视频接口")
    @PostMapping("/upload/{type}")
    public ResultVo upload(@PathVariable String type, MultipartFile file) {
        if (file.isEmpty() || file == null) {
            return ResultVo.error("上传的文件为空");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String formatted = format.format(new Date());
        File path = new File(uploadPath + "/" + type + "/" + formatted);
        if (!path.isDirectory()) {
            path.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String newName = UUID.randomUUID().toString().replace("-", "") + suffix;
        String showUrl = "/" + type + "/" + formatted + "/" + newName;
        try {
            file.transferTo(new File(path, newName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("", showUrl);
    }


}
